const express = require('express');
const axios = require('axios');
const crypto = require('crypto');
const db = require('../db');
require('dotenv').config();

const router = express.Router();

// 微信小程序配置
const WX_APP_ID = process.env.WX_APP_ID || 'wx69d7103634140d95';
const WX_APP_SECRET = process.env.WX_APP_SECRET || '';

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { code } = req.body;
    
    if (!code) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少必要参数' 
      });
    }
    
    // 调用微信API获取openid
    const wxResponse = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid: WX_APP_ID,
        secret: WX_APP_SECRET,
        js_code: code,
        grant_type: 'authorization_code'
      }
    });
    
    if (wxResponse.data.errcode) {
      return res.status(400).json({ 
        success: false, 
        message: '微信登录失败', 
        error: wxResponse.data.errmsg 
      });
    }
    
    const { openid, session_key } = wxResponse.data;
    
    // 查询用户是否已存在
    const users = await db.query('SELECT * FROM users WHERE openid = ?', [openid]);
    
    let userId;
    
    if (users.length === 0) {
      // 创建新用户
      userId = crypto.randomUUID();
      await db.query(
        'INSERT INTO users (id, openid) VALUES (?, ?)',
        [userId, openid]
      );
    } else {
      userId = users[0].id;
    }
    
    // 生成token
    const token = crypto.createHash('sha256').update(`${openid}${session_key}${Date.now()}`).digest('hex');
    
    res.json({ 
      success: true, 
      data: { 
        userId,
        token
      } 
    });
  } catch (error) {
    console.error('用户登录失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '用户登录失败', 
      error: error.message 
    });
  }
});

// 更新用户信息
router.put('/info', async (req, res) => {
  try {
    const { userId, nickname, avatarUrl } = req.body;
    
    if (!userId) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少必要参数' 
      });
    }
    
    // 更新用户信息
    await db.query(
      'UPDATE users SET nickname = ?, avatar_url = ?, updated_at = NOW() WHERE id = ?',
      [nickname || null, avatarUrl || null, userId]
    );
    
    res.json({ 
      success: true, 
      message: '用户信息更新成功' 
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '更新用户信息失败', 
      error: error.message 
    });
  }
});

// 获取用户信息
router.get('/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const users = await db.query('SELECT id, nickname, avatar_url, created_at FROM users WHERE id = ?', [userId]);
    
    if (users.length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }
    
    res.json({ 
      success: true, 
      data: users[0] 
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取用户信息失败', 
      error: error.message 
    });
  }
});

module.exports = router; 